package cn.shop.front.config;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.shop.front.util.IpUtil;
import cn.shop.utils.ApiResult;
import cn.shop.utils.annotation.NoRepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : 李一涵
 * @date : Created in 2022-7-12 13:44
 * @description :
 */
@Aspect
@Slf4j
@Component
public class NoRepeatSubmitAop {

    @Pointcut("@annotation(noRepeatSubmit)")
    public void pointCut(NoRepeatSubmit noRepeatSubmit) {

    }

    @Around(value = "pointCut(noRepeatSubmit)", argNames = "pjp,noRepeatSubmit")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String ip = IpUtil.getClientIp();
            String path = request.getRequestURI();
            SaSession session = SaSessionCustomUtil.getSessionById(ip);
            if (!session.has(path)) {
                session.set(path, 1);
                session.updateTimeout(2);
                return pjp.proceed();
            } else {
                log.info("{} 请求 {} 2秒内发生重复提交，已拒绝该次请求", ip, path);
                return ApiResult.fail("请不要重复提交");
            }
        } catch (Throwable e) {
            log.warn("", e);
            try {
                return pjp.proceed();
            } catch (Throwable ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}